# import sys
# import json
# import os
# import datetime
# from PyQt6.QtWidgets import (
#     QApplication, QMainWindow, QWidget, QHBoxLayout, QVBoxLayout,
#     QPushButton, QLabel, QStackedWidget, QLineEdit, QMessageBox,
#     QListWidget, QListWidgetItem, QMenu, QTextEdit, QFrame
# )
# from PyQt6.QtCore import Qt, QPoint
# from PyQt6.QtGui import QCursor, QPixmap
# import hashlib  # 添加用于密码加密
# # 修改为相对路径导入
# # 将项目根目录添加到 Python 路径
# project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# sys.path.insert(0, project_root)
# from modules.weather import getWeather
# from modules.list_manager import ListManager
# from modules.emotion_detection import EmoDetector


# class RegisterPage(QWidget):
#     def __init__(self, main_window):
#         super().__init__()
#         self.main_window = main_window
#         self.users_file = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'data', 'users.json')
#         layout = QVBoxLayout()

#         # 设置输入框样式
#         input_style = """
#             QLineEdit {
#                 font-size: 14px;
#                 padding: 8px;
#                 border: 1px solid #999999;  /* 更深的边框颜色 */
#                 border-radius: 6px;
#                 background-color: #F5F5F5;  /* 更深的背景颜色 */
#                 box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);  /* 更明显的阴影 */
#                 transition: all 0.3s ease;
#             }
#             QLineEdit:hover {
#                 border: 1px solid #666666;  /* 悬停时更深的边框颜色 */
#                 box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);  /* 悬停时更明显的阴影 */
#                 background-color: #EBEBEB;  /* 悬停时更深的背景颜色 */
#             }
#             QLineEdit:focus {
#                 border: 1px solid #4A90E2;  /* 聚焦时的边框颜色 */
#                 box-shadow: 0 4px 8px rgba(74, 144, 226, 0.3);  /* 聚焦时的阴影颜色加深 */
#                 background-color: #E6E6E6;  /* 聚焦时的背景颜色加深 */
#                 outline: none;
#             }
#             QLineEdit::placeholder {
#                 color: #888888;  /* 更深的占位符文字颜色 */
#                 font-style: italic;
#                 font-size: 13px;
#                 font-family: "微软雅黑";
#                 font-weight: bold;
#             }
#         """

#         # 创建输入框容器
#         input_container = QWidget()
#         input_layout = QVBoxLayout(input_container)
#         input_layout.setSpacing(0)  # 设置输入框之间的间距为0
#         input_layout.setContentsMargins(0, 0, 0, 0)  # 设置容器边距为0
#         input_container.setStyleSheet("""
#             QWidget {
#                 background: transparent;  /* 透明背景 */
#                 border-radius: 10px;
#                 padding: 10px;
#             }
#         """)

#         # 用户名输入框
#         self.username_input = QLineEdit()
#         self.username_input.setPlaceholderText("用户名")
#         self.username_input.setStyleSheet(input_style)
#         self.username_input.setAlignment(Qt.AlignmentFlag.AlignLeft)  # 设置左对齐
#         input_layout.addWidget(self.username_input)

#         # 添加分割线
#         line = QFrame()
#         line.setFrameShape(QFrame.Shape.HLine)
#         line.setFrameShadow(QFrame.Shadow.Sunken)
#         line.setStyleSheet("background-color: #cccccc;")  # 分割线颜色
#         input_layout.addWidget(line)

#         # 密码输入框
#         self.password_input = QLineEdit()
#         self.password_input.setPlaceholderText("密码")
#         self.password_input.setEchoMode(QLineEdit.EchoMode.Password)
#         self.password_input.setStyleSheet(input_style)
#         self.password_input.setAlignment(Qt.AlignmentFlag.AlignLeft)  # 设置左对齐
#         input_layout.addWidget(self.password_input)

#         # 设置输入框容器的固定宽度为窗口宽度的60%
#         input_container.setFixedWidth(int(self.width() * 0.6))
#         layout.addWidget(input_container, alignment=Qt.AlignmentFlag.AlignCenter)

#         # 注册按钮
#         self.register_button = QPushButton("注册")
#         self.register_button.clicked.connect(self.register)
#         self.register_button.setStyleSheet("""
#             QPushButton {
#                 background-color: black;
#                 color: white;
#                 border: 2px solid black;
#                 border-radius: 5px;
#                 padding: 8px 15px;
#                 font-weight: bold;
#                 min-width: 100px;
#             }
#             QPushButton:hover {
#                 background-color: #333333;
#                 border: 2px solid #333333;
#             }
#             QPushButton:pressed {
#                 background-color: #1a1a1a;
#                 border: 2px solid #1a1a1a;
#             }
#         """)
#         layout.addWidget(self.register_button)

#         # 返回登录按钮
#         self.back_button = QPushButton("返回登录")
#         self.back_button.clicked.connect(self.back_to_login)
#         layout.addWidget(self.back_button)

#         self.setLayout(layout)

#     def load_users(self):
#         if os.path.exists(self.users_file):
#             try:
#                 with open(self.users_file, 'r', encoding='utf-8') as f:
#                     return json.load(f)
#             except json.JSONDecodeError:
#                 return {}
#         return {}

#     def save_users(self, users):
#         os.makedirs(os.path.dirname(self.users_file), exist_ok=True)
#         with open(self.users_file, 'w', encoding='utf-8') as f:
#             json.dump(users, f, indent=4, ensure_ascii=False)

#     def hash_password(self, password):
#         return hashlib.sha256(password.encode()).hexdigest()

#     def register(self):
#         username = self.username_input.text().strip()
#         password = self.password_input.text()

#         if not username or not password:
#             QMessageBox.warning(self, "注册失败", "用户名和密码不能为空")
#             return

#         if len(password) < 6:
#             QMessageBox.warning(self, "注册失败", "密码长度必须至少为6个字符")
#             return

#         # 加载现有用户数据
#         users = self.load_users()

#         # 检查用户名是否已存在
#         if username in users:
#             QMessageBox.warning(self, "注册失败", "用户名已存在")
#             return

#         # 存储新用户（使用加密后的密码）
#         users[username] = {
#             "password": self.hash_password(password),
#             "created_at": str(datetime.datetime.now())
#         }

#         # 保存用户数据
#         try:
#             self.save_users(users)
#             QMessageBox.information(self, "注册成功", "注册成功！请返回登录界面进行登录")
#             self.back_to_login()
#         except Exception as e:
#             QMessageBox.critical(self, "错误", f"保存用户数据时出错：{str(e)}")

#     def back_to_login(self):
#         self.main_window.show_login()


# class LoginPage(QWidget):
#     def __init__(self, main_window):
#         super().__init__()
#         self.main_window = main_window
#         self.users_file = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'data', 'users.json')
#         layout = QVBoxLayout()

#         # 添加LOGO和标题的容器
#         logo_title_container = QWidget()
#         logo_title_layout = QVBoxLayout(logo_title_container)
#         logo_title_layout.setSpacing(0)  # 设置内部间距为0
#         logo_title_layout.setContentsMargins(0, 0, 0, 0)  # 设置外部边距为0
#         # 设置logo_title_container的背景为透明
#         logo_title_container.setStyleSheet("background: transparent;")

#         # 添加LOGO
#         logo_label = QLabel()
#         logo_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'pic', 'YL_logo2.png')
#         logo_pixmap = QPixmap(logo_path)
#         # 设置LOGO大小为100x100像素
#         logo_pixmap = logo_pixmap.scaled(100, 100, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
#         logo_label.setPixmap(logo_pixmap)
#         logo_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        
#         # 设置LOGO样式
#         logo_style = """
#             QLabel {
#                 background-color: transparent;
#                 border: 2px solid #FFD700;
#                 border-radius: 50px;
#                 padding: 1px;
#                 box-shadow: 0 0 15px rgba(255, 215, 0, 0.6);
#                 transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
#                 transform: scale(1);
#             }
#             QLabel:hover {
#                 transform: scale(1.08);
#                 border-radius: 55px;
#                 padding: 2px;
#             }
#         """
#         logo_label.setStyleSheet(logo_style)
        
#         # 设置固定大小以确保圆形效果
#         logo_label.setFixedSize(104, 104)
        
#         # 创建一个容器来放置LOGO，以便添加外发光效果
#         logo_container = QWidget()
#         logo_container.setFixedSize(110, 110)
#         logo_layout = QVBoxLayout(logo_container)
#         # 减小布局边距以确保LOGO在放大时不会被裁剪
#         logo_layout.setContentsMargins(0, 0, 0, 0)
#         logo_layout.addWidget(logo_label, alignment=Qt.AlignmentFlag.AlignCenter)
        
#         # 添加LOGO到logo_title布局
#         logo_title_layout.addWidget(logo_container, alignment=Qt.AlignmentFlag.AlignCenter)

#         # 添加"登录"标题
#         title_label = QLabel("登录")
#         title_label.setStyleSheet("""
#             QLabel {
#                 font-family: "Microsoft YaHei";
#                 font-size: 42px;
#                 font-weight: 900;
#                 color: white;  /* 修改为白色 */
#                 margin-top: -10px;  /* 使用负边距使标题上移 */
#                 padding-top: 0px;   /* 移除顶部内边距 */
#                 letter-spacing: 8px; /* 增加字间距 */
#                 text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
#             }
#         """)
#         title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
#         logo_title_layout.addWidget(title_label)

#         # 将logo_title_container添加到主布局
#         layout.addWidget(logo_title_container, alignment=Qt.AlignmentFlag.AlignCenter)

#         # 减少间距
#         layout.addSpacing(10)  # 将原来的20px间距减少到10px

#         # 设置输入框样式
#         input_style = """
#             QLineEdit {
#                 font-size: 14px;
#                 padding: 8px;
#                 border: 1px solid #999999;  /* 更深的边框颜色 */
#                 border-radius: 6px;
#                 background-color: #F5F5F5;  /* 更深的背景颜色 */
#                 box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);  /* 更明显的阴影 */
#                 transition: all 0.3s ease;
#             }
#             QLineEdit:hover {
#                 border: 1px solid #666666;  /* 悬停时更深的边框颜色 */
#                 box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);  /* 悬停时更明显的阴影 */
#                 background-color: #EBEBEB;  /* 悬停时更深的背景颜色 */
#             }
#             QLineEdit:focus {
#                 border: 1px solid #4A90E2;  /* 聚焦时的边框颜色 */
#                 box-shadow: 0 4px 8px rgba(74, 144, 226, 0.3);  /* 聚焦时的阴影颜色加深 */
#                 background-color: #E6E6E6;  /* 聚焦时的背景颜色加深 */
#                 outline: none;
#             }
#             QLineEdit::placeholder {
#                 color: #888888;  /* 更深的占位符文字颜色 */
#                 font-style: italic;
#                 font-size: 13px;
#                 font-family: "微软雅黑";
#                 font-weight: bold;
#             }
#         """

#         # 创建输入框容器
#         input_container = QWidget()
#         input_layout = QVBoxLayout(input_container)
#         input_layout.setSpacing(0)  # 设置输入框之间的间距为0
#         input_layout.setContentsMargins(0, 0, 0, 0)  # 设置容器边距为0
#         input_container.setStyleSheet("""
#             QWidget {
#                 background: transparent;  /* 透明背景 */
#                 border-radius: 10px;
#                 padding: 10px;
#             }
#         """)

#         # 用户名输入框
#         self.username_input = QLineEdit()
#         self.username_input.setPlaceholderText("用户名")
#         self.username_input.setStyleSheet(input_style)
#         self.username_input.setAlignment(Qt.AlignmentFlag.AlignLeft)  # 设置左对齐
#         input_layout.addWidget(self.username_input)

#         # 添加分割线
#         line = QFrame()
#         line.setFrameShape(QFrame.Shape.HLine)
#         line.setFrameShadow(QFrame.Shadow.Sunken)
#         line.setStyleSheet("background-color: #cccccc;")  # 分割线颜色
#         input_layout.addWidget(line)

#         # 密码输入框
#         self.password_input = QLineEdit()
#         self.password_input.setPlaceholderText("密码")
#         self.password_input.setEchoMode(QLineEdit.EchoMode.Password)
#         self.password_input.setStyleSheet(input_style)
#         self.password_input.setAlignment(Qt.AlignmentFlag.AlignLeft)  # 设置左对齐
#         input_layout.addWidget(self.password_input)

#         # 设置输入框容器的固定宽度为窗口宽度的60%
#         input_container.setFixedWidth(int(self.width() * 0.6))
#         layout.addWidget(input_container, alignment=Qt.AlignmentFlag.AlignCenter)

#         # 登录按钮
#         self.login_button = QPushButton("登录")
#         self.login_button.clicked.connect(self.login)
#         self.login_button.setStyleSheet("""
#             QPushButton {
#                 background-color: black;
#                 color: white;
#                 border: 2px solid black;
#                 border-radius: 5px;
#                 padding: 8px 15px;
#                 font-weight: bold;
#                 min-width: 100px;
#             }
#             QPushButton:hover {
#                 background-color: #333333;
#                 border: 2px solid #333333;
#             }
#             QPushButton:pressed {
#                 background-color: #1a1a1a;
#                 border: 2px solid #1a1a1a;
#             }
#         """)
#         layout.addWidget(self.login_button)

#         # 注册按钮
#         self.register_button = QPushButton("注册")
#         self.register_button.clicked.connect(self.show_register)
#         self.register_button.setStyleSheet("""
#             QPushButton {
#                 background-color: black;
#                 color: white;
#                 border: 2px solid black;
#                 border-radius: 5px;
#                 padding: 8px 15px;
#                 font-weight: bold;
#                 min-width: 100px;
#             }
#             QPushButton:hover {
#                 background-color: #333333;
#                 border: 2px solid #333333;
#             }
#             QPushButton:pressed {
#                 background-color: #1a1a1a;
#                 border: 2px solid #1a1a1a;
#             }
#         """)
#         layout.addWidget(self.register_button)

#         self.setLayout(layout)

#     def load_users(self):
#         if os.path.exists(self.users_file):
#             try:
#                 with open(self.users_file, 'r', encoding='utf-8') as f:
#                     return json.load(f)
#             except json.JSONDecodeError:
#                 return {}
#         return {}

#     def hash_password(self, password):
#         return hashlib.sha256(password.encode()).hexdigest()

#     def login(self):
#         username = self.username_input.text().strip()
#         password = self.password_input.text()

#         if not username or not password:
#             QMessageBox.warning(self, "登录失败", "用户名和密码不能为空")
#             return

#         # 加载用户数据
#         users = self.load_users()

#         # 验证用户名和密码
#         if username in users and users[username]["password"] == self.hash_password(password):
#             self.main_window.show_main_interface()
#         else:
#             QMessageBox.warning(self, "登录失败", "用户名或密码错误")

#     def show_register(self):
#         self.register_page = RegisterPage(self.main_window)
#         self.main_window.setCentralWidget(self.register_page)


# class AIQAPage(QWidget):
#     def __init__(self):
#         super().__init__()
#         layout = QVBoxLayout()

#         # 聊天显示框
#         self.chat_display = QTextEdit()
#         self.chat_display.setReadOnly(True)

#         # 输入框
#         self.input_box = QLineEdit()
#         self.input_box.returnPressed.connect(self.send_message)

#         # 模型选择按钮
#         model_layout = QHBoxLayout()
#         self.ds_button = QPushButton("DeepSeek")
#         self.db_button = QPushButton("豆包")
#         self.ds_button.setCheckable(True)
#         self.db_button.setCheckable(True)
#         self.ds_button.setChecked(True)  # 默认选择DeepSeek
#         self.ds_button.clicked.connect(lambda: self.db_button.setChecked(not self.ds_button.isChecked()))
#         self.db_button.clicked.connect(lambda: self.ds_button.setChecked(not self.db_button.isChecked()))
#         model_layout.addWidget(self.ds_button)
#         model_layout.addWidget(self.db_button)

#         # 发送按钮
#         send_button = QPushButton("发送")
#         send_button.clicked.connect(self.send_message)

#         layout.addWidget(self.chat_display)
#         layout.addLayout(model_layout)
#         layout.addWidget(self.input_box)
#         layout.addWidget(send_button)

#         self.setLayout(layout)

#     def send_message(self):
#         message = self.input_box.text()
#         if message:
#             self.chat_display.append(f"你: {message}")
#             self.input_box.clear()

#             try:
#                 # 根据选择的模型调用相应的API
#                 if self.ds_button.isChecked():
#                     from modules.ai_qa import DS
#                     response = DS(message)
#                 else:
#                     from modules.ai_qa import DB
#                     response = DB(message)

#                 self.chat_display.append(f"AI: {response}\n")
#             except Exception as e:
#                 self.chat_display.append(f"错误: 调用AI接口失败 - {str(e)}\n")


# class WeatherForecastPage(QWidget):
#     def __init__(self):
#         super().__init__()
#         layout = QVBoxLayout()

#         # 城市输入框
#         self.city_input = QLineEdit()
#         self.city_input.setPlaceholderText("请输入城市名称")
#         layout.addWidget(self.city_input)

#         # 获取天气按钮
#         self.get_weather_button = QPushButton("获取天气")
#         self.get_weather_button.clicked.connect(self.get_weather)
#         layout.addWidget(self.get_weather_button)

#         # 天气显示标签
#         self.weather_label = QLabel("请输入城市并点击获取天气")
#         layout.addWidget(self.weather_label)

#         self.setLayout(layout)

#     def get_weather(self):
#         city = self.city_input.text().strip()
#         if city:
#             try:
#                 # 调用 weather.py 中的函数获取天气信息
#                 getWeather(city)
#                 with open('temp/temp.json', 'r') as f:
#                     data = json.load(f)
#                 weather_info = ""
#                 for item in data['weatherlist']:
#                     weather_info += f"日期: {item['date']}\n"
#                     weather_info += f"白天天气: {item['climate1']}\n"
#                     weather_info += f"白天风向: {item['windDirection1']}\n"
#                     weather_info += f"白天风力: {item['windPower1']}\n"
#                     weather_info += f"最高温度: {item['high']}\n"
#                     weather_info += f"最低温度: {item['low']}\n"
#                     weather_info += f"夜间天气: {item['climate2']}\n"
#                     weather_info += f"夜间风向: {item['windDirection2']}\n"
#                     weather_info += f"夜间风力: {item['windPower2']}\n\n"
#                 self.weather_label.setText(weather_info)
#             except Exception as e:
#                 self.weather_label.setText(f"获取天气信息出错: {str(e)}")
#         else:
#             self.weather_label.setText("请输入有效的城市名称")


# class TaskListPage(QWidget):
#     def __init__(self):
#         super().__init__()
#         self.list_manager = ListManager()
#         self.project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#         self.setup_ui()
#         self.is_standby = False
#         self.task_items = {}  # 任务ID到列表项的映射
#         self.filename_to_task_id = {}  # 文件名到任务ID的映射

#     def setup_ui(self):
#         layout = QVBoxLayout()

#         # 任务输入区域
#         input_layout = QHBoxLayout()
#         self.task_input = QLineEdit()
#         self.add_button = QPushButton("添加任务")
#         self.add_button.clicked.connect(self.add_task)
#         input_layout.addWidget(self.task_input)
#         input_layout.addWidget(self.add_button)

#         # 任务列表区域
#         self.task_display = QListWidget()
#         self.task_display.setSelectionMode(QListWidget.SelectionMode.SingleSelection)
#         self.task_display.itemClicked.connect(self.on_task_selected)

#         # 删除按钮
#         self.delete_button = QPushButton("删除选中任务")
#         self.delete_button.setEnabled(False)
#         self.delete_button.clicked.connect(self.delete_selected_task)

#         # 主布局
#         layout.addLayout(input_layout)
#         layout.addWidget(self.task_display)
#         layout.addWidget(self.delete_button)
#         self.setLayout(layout)

#         # 初始刷新
#         self.refresh_tasks()

#     def add_task(self):
#         task_text = self.task_input.text().strip()
#         if task_text:
#             try:
#                 self.list_manager.process(task_text)
#                 self.task_input.clear()
#                 self.refresh_tasks()
#                 QMessageBox.information(self, "成功", "任务添加成功！")
#             except Exception as e:
#                 QMessageBox.warning(self, "错误", f"添加任务失败：{str(e)}")

#     def refresh_tasks(self):
#         self.task_display.clear()
#         self.task_items = {}
#         self.filename_to_task_id = {}

#         todo_dir = os.path.join(self.project_root, "todo_lists")
#         print(f"任务列表目录: {todo_dir}")

#         if not os.path.exists(todo_dir):
#             self.task_display.addItem("暂无任务")
#             return

#         try:
#             for filename in sorted(os.listdir(todo_dir), reverse=True):
#                 if filename.endswith('.json'):
#                     file_path = os.path.join(todo_dir, filename)
#                     try:
#                         with open(file_path, 'r', encoding='gbk') as f:
#                             task_data = json.load(f)

#                         task_id = task_data.get("task_id")
#                         if not task_id:
#                             print(f"文件 {filename} 缺少task_id字段")
#                             continue

#                         # 提取文件名中的时间戳部分
#                         file_timestamp = filename.replace("task_", "").replace(".json", "")

#                         # 保存文件名到任务ID的映射
#                         self.filename_to_task_id[file_timestamp] = task_id

#                         item = QListWidgetItem()
#                         item.setText(f"{task_data['time']} | {task_data['username']} | {task_data['event']}")
#                         item.setData(Qt.ItemDataRole.UserRole, task_id)

#                         self.task_display.addItem(item)
#                         self.task_items[task_id] = item

#                     except Exception as e:
#                         print(f"读取任务文件失败 {filename}: {str(e)}")

#         except Exception as e:
#             self.task_display.addItem(f"加载任务列表失败: {str(e)}")

#     def on_task_selected(self, item):
#         self.delete_button.setEnabled(True)

#     def delete_selected_task(self):
#         selected_items = self.task_display.selectedItems()
#         if not selected_items:
#             QMessageBox.warning(self, "提示", "请先选择要删除的任务")
#             return

#         item = selected_items[0]
#         task_id = item.data(Qt.ItemDataRole.UserRole)

#         if not task_id:
#             QMessageBox.warning(self, "错误", "无法获取任务ID")
#             return

#         try:
#             todo_dir = os.path.join(self.project_root, "todo_lists")

#             # 尝试通过任务ID查找文件名
#             file_found = False
#             file_to_delete = None

#             # 方式1: 直接使用任务ID作为文件名
#             possible_file1 = os.path.join(todo_dir, f"task_{task_id}.json")
#             if os.path.exists(possible_file1):
#                 file_to_delete = possible_file1
#                 file_found = True

#             # 方式2: 通过文件名到任务ID的映射查找
#             if not file_found:
#                 for filename, stored_task_id in self.filename_to_task_id.items():
#                     if stored_task_id == task_id:
#                         possible_file2 = os.path.join(todo_dir, f"task_{filename}.json")
#                         if os.path.exists(possible_file2):
#                             file_to_delete = possible_file2
#                             file_found = True
#                             break

#             # 方式3: 尝试所有文件，查找包含该任务ID的文件
#             if not file_found:
#                 for filename in os.listdir(todo_dir):
#                     if filename.endswith('.json'):
#                         file_path = os.path.join(todo_dir, filename)
#                         try:
#                             with open(file_path, 'r', encoding='gbk') as f:
#                                 data = json.load(f)
#                                 if data.get("task_id") == task_id:
#                                     file_to_delete = file_path
#                                     file_found = True
#                                     break
#                         except:
#                             continue

#             if not file_found:
#                 QMessageBox.warning(self, "错误", f"找不到任务文件: {task_id}")
#                 print("当前目录下的文件列表:")
#                 for f in os.listdir(todo_dir):
#                     print(f"- {f}")
#                 return

#             # 删除文件
#             os.remove(file_to_delete)
#             QMessageBox.information(self, "成功", "任务已删除")
#             self.refresh_tasks()
#             self.delete_button.setEnabled(False)

#         except Exception as e:
#             QMessageBox.warning(self, "错误", f"删除任务失败: {str(e)}")

#     # 拖动功能
#     def mousePressEvent(self, event):
#         if self.is_standby:
#             self.oldPos = event.globalPos()

#     def mouseMoveEvent(self, event):
#         if self.is_standby and hasattr(self, 'oldPos'):
#             delta = event.globalPos() - self.oldPos
#             self.move(self.x() + delta.x(), self.y() + delta.y())
#             self.oldPos = event.globalPos()


# class EntertainmentPage(QWidget):
#     def __init__(self, parent=None):
#         super().__init__(parent)
#         self.emotion_detector = EmoDetector()
#         self.setup_ui()

#     def setup_ui(self):
#         layout = QVBoxLayout()

#         # 添加标题
#         title_label = QLabel("情绪分析")
#         title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
#         title_label.setStyleSheet("font-size: 18px; font-weight: bold; margin: 10px;")
#         layout.addWidget(title_label)

#         # 用户输入区域
#         self.input_box = QTextEdit()
#         self.input_box.setPlaceholderText("请输入你现在的心情...")
#         self.input_box.setMaximumHeight(100)
#         layout.addWidget(self.input_box)

#         # 分析按钮
#         self.analyze_button = QPushButton("分析心情")
#         self.analyze_button.clicked.connect(self.analyze_emotion)
#         layout.addWidget(self.analyze_button)

#         # 情绪分析结果显示区域
#         self.result_display = QTextEdit()
#         self.result_display.setReadOnly(True)
#         self.result_display.setPlaceholderText("分析结果将在这里显示...")
#         layout.addWidget(self.result_display)

#         self.setLayout(layout)

#     def analyze_emotion(self):
#         user_input = self.input_box.toPlainText()
#         if user_input:
#             try:
#                 result = self.emotion_detector.emotion_detection(
#                     user_response=user_input,
#                     user_data={"user_id": "default", "name": "用户", "location": "北京", "age": 25},
#                     city="北京"
#                 )
#                 if result and "emotion_analysis" in result:
#                     analysis = result["emotion_analysis"]
#                     display_text = f"情绪分析结果：\n\n"
#                     display_text += f"主要情绪：{analysis.get('emotion', '未知')}\n"
#                     display_text += f"情绪强度：{analysis.get('intensity', '未知')}/5\n"
#                     display_text += f"置信度：{analysis.get('confidence', 0):.2f}\n"
#                     display_text += f"影响因素：{', '.join(analysis.get('contributing_factors', ['未知']))}\n"
#                     display_text += f"\n建议：{analysis.get('suggestion', '暂无建议')}"
#                     self.result_display.setText(display_text)
#                 else:
#                     self.result_display.setText("分析失败，请稍后重试")
#             except Exception as e:
#                 self.result_display.setText(f"分析出错：{str(e)}")
#         else:
#             self.result_display.setText("请先输入你的心情...")


# class MainWindow(QMainWindow):
#     def __init__(self):
#         super().__init__()
#         self.initUI()
#         self.show_login()
#         self.is_standby = False
#         self.is_entertainment = False  # 添加娱乐模式标志
#         self.last_pos = None
#         self.dragging = False
#         self.emotion_detector = EmoDetector()  # 初始化情绪检测器

#     def initUI(self):
#         # 创建主部件
#         main_widget = QWidget()
#         # 创建主布局
#         main_layout = QHBoxLayout()

#         # 创建左侧frame
#         self.left_frame = QFrame()
#         self.left_frame.setFixedSize(400, 400)  
#         self.left_frame.setStyleSheet("""
#             QFrame {
#                 background-image: url('pic/welcome.png');
#                 background-repeat: no-repeat;
#                 background-position: center;
#                 background-size: cover;
#             }
#         """)
#         main_layout.addWidget(self.left_frame)

#         # 创建右侧界面
#         right_widget = QWidget()
#         right_layout = QVBoxLayout(right_widget)
#         right_layout.setAlignment(Qt.AlignmentFlag.AlignRight)  # 设置右对齐

#         # 创建按钮布局
#         button_layout = QVBoxLayout()

#         # 创建按钮
#         self.ai_qa_button = QPushButton("AI 问答")
#         self.weather_button = QPushButton("天气预报")
#         self.task_list_button = QPushButton("任务列表")
#         self.entertainment_button = QPushButton("娱乐模式")  # 新增娱乐模式按钮
#         self.mode_button = QPushButton("切换待机模式")

#         # 设置按钮样式
#         button_style = """
#             QPushButton {
#                 background-color: #3498db;
#                 color: white;
#                 border: 2px solid #2980b9;
#                 border-radius: 5px;
#                 padding: 8px 15px;
#                 font-weight: bold;
#                 min-width: 100px;
#             }
#             QPushButton:hover {
#                 background-color: #2980b9;
#                 border: 2px solid #2475a8;
#             }
#             QPushButton:pressed {
#                 background-color: #2475a8;
#                 border: 2px solid #1c6ea4;
#             }
#         """
#         self.ai_qa_button.setStyleSheet(button_style)
#         self.weather_button.setStyleSheet(button_style)
#         self.task_list_button.setStyleSheet(button_style)
#         self.entertainment_button.setStyleSheet(button_style)
#         self.mode_button.setStyleSheet(button_style)

#         # 连接按钮点击事件
#         self.ai_qa_button.clicked.connect(self.show_ai_qa_page)
#         self.weather_button.clicked.connect(self.show_weather_page)
#         self.task_list_button.clicked.connect(self.show_task_list_page)
#         self.entertainment_button.clicked.connect(self.show_entertainment_page)  # 新增事件连接
#         self.mode_button.clicked.connect(self.toggle_mode)

#         # 将按钮添加到按钮布局
#         button_layout.addWidget(self.ai_qa_button)
#         button_layout.addWidget(self.weather_button)
#         button_layout.addWidget(self.task_list_button)
#         button_layout.addWidget(self.entertainment_button)  # 添加娱乐模式按钮
#         button_layout.addWidget(self.mode_button)
#         button_layout.addStretch()

#         # 创建堆叠窗口部件
#         self.stacked_widget = QStackedWidget()

#         # 创建不同页面
#         self.ai_qa_page = AIQAPage()
#         self.weather_page = WeatherForecastPage()
#         self.task_list_page = TaskListPage()
#         self.entertainment_page = EntertainmentPage(self)  # 修改这里，传入self作为父窗口

#         # 将页面添加到堆叠窗口部件
#         self.stacked_widget.addWidget(self.ai_qa_page)
#         self.stacked_widget.addWidget(self.weather_page)
#         self.stacked_widget.addWidget(self.task_list_page)
#         self.stacked_widget.addWidget(self.entertainment_page)

#         # 将按钮布局和堆叠窗口部件添加到主布局
#         right_layout.addLayout(button_layout)
#         main_layout.addWidget(right_widget)

#         # 将主布局设置给主部件
#         main_widget.setLayout(main_layout)

#         # 将主部件设置为中心部件
#         self.setCentralWidget(main_widget)

#         # 设置主界面背景图片（相对路径，适中透明度）
#         base_img_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'pic', 'base.png')
#         if os.path.exists(base_img_path):
#             base_img_path_qt = base_img_path.replace('\\', '/')
#             self.setStyleSheet(f"""
#                 QMainWindow {{
#                     background-image: url('{base_img_path_qt}');
#                     background-repeat: no-repeat;
#                     background-position: center;
#                     background-size: cover;
#                 }}
#             """)
#         else:
#             print(f"背景图片不存在: {base_img_path}")

#         # 设置窗口属性
#         self.setWindowTitle('YL桌面助手')
#         # 移除固定大小限制，允许自由拉伸
#         screen = QApplication.primaryScreen().geometry()
#         x_pos = (screen.width() - 400) // 2
#         y_pos = (screen.height() - 400) // 2
#         self.move(x_pos, y_pos)  # 将窗口移动到屏幕中央

#     def toggle_mode(self):
#         self.is_standby = not self.is_standby
#         if self.is_standby:
#             # 待机模式：只显示任务列表
#             self.setWindowTitle('待机模式 - 待办事项')
#             self.mode_button.setText("⚙️")
#             self.mode_button.setStyleSheet("""
#                 QPushButton {
#                     max-width: 30px;
#                     min-width: 30px;
#                     max-height: 30px;
#                     min-height: 30px;
#                     border-radius: 15px;
#                     background-color: #f0f0f0;
#                 }
#                 QPushButton:hover {
#                     background-color: #e0e0e0;
#                 }
#             """)
#             self.ai_qa_button.hide()
#             self.weather_button.hide()
#             self.task_list_button.hide()
#             self.entertainment_button.hide()
#             self.stacked_widget.setCurrentWidget(self.task_list_page)
#             self.task_list_page.set_standby_mode(True)

#             # 设置到右上角
#             screen = QApplication.primaryScreen().geometry()
#             window_width = 300
#             window_height = 300
#             x_pos = screen.width() - window_width - 10
#             y_pos = 10
#             self.last_pos = QPoint(x_pos, y_pos)

#             # 设置无边框和置顶
#             self.setWindowFlags(Qt.WindowType.FramelessWindowHint | Qt.WindowType.WindowStaysOnTopHint)
#             # 调整窗口大小和位置
#             self.setGeometry(self.last_pos.x(), self.last_pos.y(), window_width, window_height)
#             self.show()
#         else:
#             # 工作模式：显示所有功能
#             self.task_list_page.set_standby_mode(False)
#             self.setWindowTitle('YL桌面助手')
#             self.mode_button.setText("切换待机模式")
#             self.mode_button.setStyleSheet("")
#             self.ai_qa_button.show()
#             self.weather_button.show()
#             self.task_list_button.show()
#             self.entertainment_button.show()
#             self.mode_button.show()

#             # 恢复窗口标志
#             self.setWindowFlags(Qt.WindowType.Window)

#             # 设置到屏幕中央
#             screen = QApplication.primaryScreen().geometry()
#             window_width = 800
#             window_height = 800
#             x_pos = (screen.width() - window_width) // 2
#             y_pos = (screen.height() - window_height) // 2
#             self.last_pos = QPoint(x_pos, y_pos)

#             # 恢复原始窗口大小和位置，但不限制大小
#             self.setGeometry(self.last_pos.x(), self.last_pos.y(), window_width, window_height)
#             self.show()

#     def mousePressEvent(self, event):
#         if self.is_standby and event.button() == Qt.MouseButton.LeftButton:
#             self.dragging = True
#             self.drag_position = event.globalPosition().toPoint() - self.frameGeometry().topLeft()
#             event.accept()

#     def mouseMoveEvent(self, event):
#         if self.is_standby and self.dragging:
#             self.move(event.globalPosition().toPoint() - self.drag_position)
#             event.accept()

#     def mouseReleaseEvent(self, event):
#         if self.is_standby and event.button() == Qt.MouseButton.LeftButton:
#             self.dragging = False
#             self.last_pos = self.pos()  # 更新保存的位置
#             event.accept()

#     def show_login(self):
#         self.login_page = LoginPage(self)
#         self.setCentralWidget(self.login_page)

#     def show_main_interface(self):
#         main_widget = QWidget()
#         main_layout = QHBoxLayout()

#         # 设置主界面背景图片
#         base_img_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'pic', 'base.png')
#         if os.path.exists(base_img_path):
#             base_img_path_qt = base_img_path.replace('\\', '/')
#             main_widget.setStyleSheet(f"""
#                 QWidget {{
#                     background-image: url('{base_img_path_qt}');
#                     background-repeat: no-repeat;
#                     background-position: center;
#                     background-size: cover;
#                 }}
#             """)
#         else:
#             print(f"背景图片不存在: {base_img_path}")

#         # 创建按钮布局
#         button_layout = QVBoxLayout()

#         # 创建按钮
#         self.ai_qa_button = QPushButton("AI 问答")
#         self.weather_button = QPushButton("天气预报")
#         self.task_list_button = QPushButton("任务列表")
#         self.entertainment_button = QPushButton("娱乐模式")  # 添加娱乐模式按钮
#         self.mode_button = QPushButton("切换待机模式")

#         # 设置按钮样式
#         button_style = """
#             QPushButton {
#                 background-color: #3498db;
#                 color: white;
#                 border: 2px solid #2980b9;
#                 border-radius: 5px;
#                 padding: 8px 15px;
#                 font-weight: bold;
#                 min-width: 100px;
#             }
#             QPushButton:hover {
#                 background-color: #2980b9;
#                 border: 2px solid #2475a8;
#             }
#             QPushButton:pressed {
#                 background-color: #2475a8;
#                 border: 2px solid #1c6ea4;
#             }
#         """
#         self.ai_qa_button.setStyleSheet(button_style)
#         self.weather_button.setStyleSheet(button_style)
#         self.task_list_button.setStyleSheet(button_style)
#         self.entertainment_button.setStyleSheet(button_style)
#         self.mode_button.setStyleSheet(button_style)

#         # 连接按钮点击事件
#         self.ai_qa_button.clicked.connect(self.show_ai_qa_page)
#         self.weather_button.clicked.connect(self.show_weather_page)
#         self.task_list_button.clicked.connect(self.show_task_list_page)
#         self.entertainment_button.clicked.connect(self.show_entertainment_page)  # 添加事件连接
#         self.mode_button.clicked.connect(self.toggle_mode)

#         # 将按钮添加到按钮布局
#         button_layout.addWidget(self.ai_qa_button)
#         button_layout.addWidget(self.weather_button)
#         button_layout.addWidget(self.task_list_button)
#         button_layout.addWidget(self.entertainment_button)  # 添加娱乐模式按钮到布局
#         button_layout.addWidget(self.mode_button)
#         button_layout.addStretch()

#         # 创建堆叠窗口部件
#         self.stacked_widget = QStackedWidget()

#         # 创建不同页面
#         self.ai_qa_page = AIQAPage()
#         self.weather_page = WeatherForecastPage()
#         self.task_list_page = TaskListPage()
#         self.entertainment_page = EntertainmentPage()  # 添加娱乐模式页面

#         # 将页面添加到堆叠窗口部件
#         self.stacked_widget.addWidget(self.ai_qa_page)
#         self.stacked_widget.addWidget(self.weather_page)
#         self.stacked_widget.addWidget(self.task_list_page)
#         self.stacked_widget.addWidget(self.entertainment_page)  # 添加娱乐模式页面到堆叠窗口

#         # 将按钮布局和堆叠窗口部件添加到主布局
#         main_layout.addLayout(button_layout)
#         main_layout.addWidget(self.stacked_widget)

#         # 将主布局设置给主部件
#         main_widget.setLayout(main_layout)

#         # 将主部件设置为中心部件
#         self.setCentralWidget(main_widget)

#     def show_ai_qa_page(self):
#         self.stacked_widget.setCurrentWidget(self.ai_qa_page)

#     def show_weather_page(self):
#         self.stacked_widget.setCurrentWidget(self.weather_page)

#     def show_task_list_page(self):
#         self.stacked_widget.setCurrentWidget(self.task_list_page)

#     def show_entertainment_page(self):
#         self.stacked_widget.setCurrentWidget(self.entertainment_page)


# if __name__ == '__main__':
#     app = QApplication(sys.argv)

#     # 加载样式表（添加错误处理）
#     try:
#         style_file = os.path.join(os.path.dirname(__file__), 'styles.qss')
#         if os.path.exists(style_file):
#             with open(style_file, 'r', encoding='utf-8') as f:
#                 style = f.read()
#                 app.setStyleSheet(style)
#         else:
#             print(f"样式文件不存在: {style_file}")
#     except Exception as e:
#         print(f"加载样式文件失败: {str(e)}")

#     window = MainWindow()
#     window.show()
#     sys.exit(app.exec())